package leecode

import "sort"

func merge(intervals [][]int) [][]int {
	if len(intervals) < 2 {
		return intervals
	}
	//按照第一列进行升序排列
	sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
	result := [][]int{intervals[0]}
	for i := 1; i < len(intervals); i++ {
		if intervals[i][0] <= result[len(result)-1][1] {
			if intervals[i][1] > result[len(result)-1][1] {
				result[len(result)-1][1] = intervals[i][1]
			}
		} else {
			//当区间无法合并的时候,直接追加到result切片后
			result = append(result, intervals[i])
		}
	}
	return result
}
